import router from "@/router";
import axios from "axios";

//请求
axios.interceptors.request.use((config) => {
  //配置基础url，以后所有请求地址自动携带api
  config.baseURL = "/";
  if (localStorage.getItem("token")) {
    config.headers.token = localStorage.getItem("token");
  }
  return config;
});

// 拦截器跳转登录页
axios.interceptors.response.use(
  (response) => {
    if (response.data.code == 0 && response.status == 200) {
      localStorage.removeItem("token");
      router.replace({
        path: "/login/login",
      });
    }
    return response;
  },
  (error) => {}
);

const http = {
  /** get 请求
   * @param  {接口地址} url
   * @param  {请求配置} config
   */
  get(url, config) {
    return new Promise((resolve, reject) => {
      instance
        .get(url, config)
        .then((response) => {
          if (response) resolve(response.data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  /** post 请求
   * @param  {接口地址} url
   * @param  {请求数据} data
   * @param  {配置} config
   */
  post(url, data, config) {
    return new Promise((resolve, reject) => {
      instance
        .post(url, data, config)
        .then((response) => {
          console.log(response);
          if (response) resolve(response.data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  /** delete 请求
   * @param  {接口地址} url
   * @param  {请求配置} config
   */
  delete(url, config) {
    return new Promise((resolve, reject) => {
      instance
        .delete(url, {
          data: config,
        })
        .then((response) => {
          if (response) resolve(response.data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  /** put 请求
   * @param  {接口地址} url
   * @param  {请求配置} config
   */
  put(url, config) {
    return new Promise((resolve, reject) => {
      instance
        .put(url, config)
        .then((response) => {
          if (response) resolve(response.data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
};

export default axios;
// export default http;
